import { ChapterContext } from '@/hooks/useChapterContext'
import BaseNode from '@/Model/Node/BaseNode'
import CommonNode from '@/Model/Node/CommonNode'
import DecisionNode from '@/Model/Node/DecisionNode'
import { Dispatch, SetStateAction, useContext } from 'react'
import { v4 as uuidv4 } from 'uuid'

export default function useEditor (nodeId:string) {
  const cahpterContext = useContext(ChapterContext)
  const [chapter, setChapter] = cahpterContext?.chapter
  const [currentCard, setCurrentCard] = cahpterContext.currentCard

  const [_, setRefresh] = cahpterContext.refresh

  const handleOnChangeTitle = (event:any) => {
    const newNode = {
      ...chapter.nodes[nodeId],
      title: event.target.value
    }
    chapter.nodes[nodeId] = newNode
    reRender()
  }

  const handleOnChangeDesc = (event:any) => {
    const newNode = {
      ...chapter.nodes[nodeId],
      desc: event.target.value
    }
    chapter.nodes[nodeId] = newNode
    reRender()
  }

  const handleOnChangeNext = (event:any) => {
    const newNode = {
      ...chapter.nodes[nodeId],
      next: event.target.value
    }
    chapter.nodes[nodeId] = newNode
    reRender()
  }

  const handleOnChangePrev = (event:any) => {
    const newNode = {
      ...chapter.nodes[nodeId],
      prev: event.target.value
    }
    chapter.nodes[nodeId] = newNode
    reRender()
  }

  const handleOnChangeAction = (event:any) => {
    const newNode = {
      ...chapter.nodes[nodeId],
      action: event.target.value
    }
    chapter.nodes[nodeId] = newNode
    reRender()
  }

  const reRender = () => {
    setRefresh(new Date().getTime())
  }

  const addCommonNode = () => {
    const uuid = uuidv4()
    const commonNode = new CommonNode(uuid)
    commonNode.prev = nodeId
    chapter.nodes[nodeId].next = uuid
    chapter.nodes[uuid] = commonNode
    reRender()
  }

  const addDecisionNode = () => {
    const uuid = uuidv4()
    const decisionNode = new DecisionNode(uuid)
    decisionNode.prev = nodeId
    chapter.nodes[nodeId].next = uuid
    chapter.nodes[uuid] = decisionNode
    reRender()
  }

  const delNode = () => {
    let nextId = ''
    if (chapter.nodes[nodeId]?.prev) {
      nextId = chapter.nodes[nodeId]?.prev
    } else if (chapter.nodes[nodeId]?.next) {
      nextId = chapter.nodes[nodeId]?.next
    }
    delete chapter.nodes[chapter.nodes[nodeId].uuid]
    setTimeout(() => {
      setCurrentCard(nextId)
    }, 100)
  }

  const toNext = (e:any) => {
    e.stopPropagation()
    setCurrentCard(chapter.nodes[nodeId].next)
  }

  const toPrev = (e:any) => {
    e.stopPropagation()
    setCurrentCard(chapter.nodes[nodeId].prev)
  }

  return {
    handleOnChangeTitle,
    handleOnChangeDesc,
    handleOnChangeAction,
    setCurrentCard,
    currentCard,
    addCommonNode,
    addDecisionNode,
    handleOnChangeNext,
    handleOnChangePrev,
    delNode,
    reRender,
    toNext,
    toPrev
  }
}
